<script setup lang="ts">
import { computed } from "vue";
import Taro, { useRouter } from "@tarojs/taro";

import ByPage from "@/components/ui/ByPage.vue";
import ByEmpty from "@/components/ui/ByEmpty.vue";
import ByButton from "@/components/ui/ByButton.vue";
import ViewList from "@/components/common/ViewList.vue";
import CouponItem from "@/pages/coupon/components/CouponItem.vue";

import ApiTicket from "@/api/ticket";
import useList from "@/hooks/useList";
import useFetch from "@/hooks/useFetch";

const { params } = useRouter<{
  scene: string;
}>();

const batch_num = decodeURIComponent(params.scene);

const toIndexPage = () => {
  Taro.switchTab({ url: "/pages/coupon/index" });
};

// 接收转赠票券
const { loading, run } = useFetch<any>(ApiTicket.userTicketReceive, {
  immediate: false,
  onSuccess() {
    Taro.showToast({ title: "接收成功！" });
    setTimeout(() => {
      toIndexPage();
    }, 1500);
  },
});

// 根据batch_num返回包含的票券列表
const { list } = useList<{
  id: number;
  status: number;
}>(ApiTicket.userTicketList, {
  showLoading: true,
  immediate: !!batch_num,
  search: { batch_num },
});

/**
 * 是否已经接收过票券
 * @return true 还未接收
 */
const notAccepted = computed(() => {
  const target = list.value[0];
  return target?.status == 4;
});
</script>

<template>
  <ByPage check-login footer-fixed footer-safe :bodyCenter="!notAccepted">
    <template #footer>
      <view class="text-center pb-3" v-if="notAccepted && list.length > 0">
        <ByButton
          class="w-1/2 bg-dark"
          :loading="loading"
          @tap="run({ batch_num })"
          >收下票券
        </ByButton>
      </view>
    </template>

    <ViewList
      v-if="notAccepted"
      :loading="loading"
      :is-empty="list.length == 0"
    >
      <view class="mx-3 my-4" v-for="item in list" :key="item.id">
        <CouponItem selection :source="item" />
      </view>
    </ViewList>

    <View class="flex-auto text-center -translate-y-1/2" v-else>
      <ByEmpty title="票券已被领取~" />
      <ByButton class="w-1/2 mt-6" @tap="toIndexPage">前往票券页</ByButton>
    </View>
  </ByPage>
</template>

<style lang="less">
page {
  background: linear-gradient(to bottom, #fef7ee, #dec2a0);
}
</style>
